package com.ben.multiple.aop.config;

import java.time.LocalDateTime;
import java.util.Objects;

import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
public class LogAspect {

    @Around(value = "@annotation(logAnnotation)")
    public Object around(ProceedingJoinPoint point, LogAnnotation logAnnotation) throws Throwable {
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes());
//        HttpServletRequest request = servletRequestAttributes.getRequest();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String methodName = point.getSignature().toLongString();
        Log log = new Log();
        log.setId(1);
        log.setTime(LocalDateTime.now());
        log.setRemark(logAnnotation.value());
        log.setMethod(methodName);
        log.setRemoteUrl(request.getRequestURL().toString());
        log.setRemoteIp("");
        Long startTime = System.currentTimeMillis();
        Object obj = point.proceed();
        Long endTime = System.currentTimeMillis();
        log.setProcessTime((int) (endTime - startTime));
        // 发布日志事件
        SpringContextHolder.publishEvent(new LogEvent(log));
        return obj;
    }
}
